import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, customResponse } from '~/utils/response';
import { queryDatabase, generateFiles, formatDateTime, processedSampleArr } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    // 读取POST请求的请求体，获取查询参数
    const { type: filesType, sampleNoArray, outputMode } = await readBody(event);
    if (!filesType || !sampleNoArray) throw new Error('缺少参数');

    // 查询数据库，获取对应的数据
    let queryString = `SELECT * FROM samplelists WHERE sampleNo IN (?)`;
    const data = <any[]>await queryDatabase(queryString, [sampleNoArray]);
    if (!data || data.length < 1) throw new Error('查询数据库失败');
    // console.log('数据库查询结果：', data);

    // 转译数据，将processedSampleArr转换为对象
    const sampleMap = Object.fromEntries(processedSampleArr.map((item) => [item.label, item.value]));
    const sampleNameVal = (sampleName: string) => {
      if (sampleName.startsWith('[')) {
        if (JSON.parse(sampleName).length > 1) {
          return sampleMap[JSON.parse(sampleName).join('-')].split('-')[1];
        } else {
          return sampleMap[JSON.parse(sampleName)];
        }
      } else {
        return sampleName;
      }
    };
    const processTableData = (data) => {
      try {
        const rawData = JSON.parse(data);
        return Array.isArray(rawData) ? rawData : [rawData];
      } catch (error) {
        return [];
      }
    };
    // 处理每个数据，使其符合模板要求
    const newData = data.map((item) => {
      const outputName =
        filesType === 'report' ? `${item.reportNo.replace(/\//g, '')}` : `${item.orderNo.replace(/\//g, '')}`;

      item.sampleName = sampleNameVal(item.sampleName);
      item.analysisDate = formatDateTime(item.analysisDate, 'dateCN');
      item.receiveDate = formatDateTime(item.receiveDate, 'dateCN');
      item.reportTable = processTableData(item.reportTable).map((item) => {
        item.testMethod = item.testMethod.split('《')[0];
        return item;
      });
      item.instTable = processTableData(item.instTable);
      return {
        outputName: outputName,
        data: item,
      };
    });

    // 根据查询结果生成文件
    const files = await generateFiles({
      templateName: 'CNAS_Report.docx',
      data: newData,
      outputMode: outputMode,
    });

    return useResponseSuccess(files);
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
